package com.joker.registration.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joker.registration.cmn.listener.DictListener;
import com.joker.registration.cmn.service.DictService;
import com.joker.registration.cmn.mapper.DictMapper;
import model.com.manubao.yygh.model.cmn.Dict;
import model.com.manubao.yygh.vo.cmn.DictEeVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import util.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
* @author 20405
* @description 针对表【dict(组织架构表)】的数据库操作Service实现
* @createDate 2022-03-22 15:56:01
*/
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements DictService{


    //注@Cacheable使用springframework中的
    /**
     * 表示该方法的返回值存入缓存，命名：dict
     * keyGenerator表示根据当前方法的包名、类名、方法名生成key（唯一效果）
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChlidData(Long id) {
//条件构造器
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            //通过查询判断每个节点下面是否还有子节点
            boolean isChild = this.isChildren(dictId);
            //修改hasChildren的值
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    /**
     * 判断id下面是否有子节点（并不查询出来）
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        //count 0>0    1>0
        return count>0;
    }

    //导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置下载信息（导出就类似下载）
            response.setContentType("application/vnd.ms-excel");  //文件类型是excel
            response.setCharacterEncoding("utf-8"); //编码
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8"); //文件名及文件名编码
            // 也可以直接设置个名字：String fileName = "dict";
            response.setHeader("Content-disposition", "attachment;filename="+ fileName +".xlsx");
            //设置请求头，让操作以下载方式打开

            //查询数据库
            List<Dict> dictList = baseMapper.selectList(null);
            //将Dict对象转换成DictEeVo对象
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                //转换
                BeanUtils.copyProperties(dict, dictEeVo);
                dictVoList.add(dictEeVo);
            }
            //写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入数据字典
    /**
     * 清空指定dict的缓存数据
     * allEntries=true表示清空所有缓存
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




